package cn.edu.nju.ws.sview.servlets;

import java.io.IOException;
import java.util.HashSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.nju.ws.sview.mail.Email;
import cn.edu.nju.ws.sview.util.MD5;
import cn.edu.nju.ws.sview.views.User_validate;

/**
 * Servlet implementation class ConfirmMail
 */
@WebServlet("/ConfirmMail")
public class ConfirmMail extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ConfirmMail() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uid = request.getParameter("uid");
		String pwd = request.getParameter("pwd") ;
		String email = request.getParameter("email") ;
		String displayLang = request.getParameter("display-lang") ;
		String from = request.getParameter("from");
		String chain_lang=(String)request.getSession().getAttribute("lang");
		String[] preferLangs = request.getParameterValues("prefer-langs");
		System.out.println(pwd+"---"+MD5.makeMD5Str(pwd));
		User_validate user_validate = new User_validate(uid);
		String code=uid+Email.generateCode(8);
		user_validate.setPassword(MD5.makeMD5Str(pwd)) ;
		user_validate.setEmail(email);
		HashSet<String> langs=new HashSet<String>();
		for(String lang:preferLangs){
			langs.add(lang) ;
		}
		user_validate.setLanguages(langs) ;
		user_validate.setDisplayLang(displayLang);
		try {
			user_validate.serialize(code);
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		user_validate.serializePasswordEmail();
		try {
			user_validate.serializePreferredLanguages();
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		user_validate.serializeDisplayLanguage();
		request.getSession().setAttribute("from", from);
		request.getSession().setAttribute("code", code);
		request.getSession().setAttribute("email", email);
		request.getSession().setAttribute("lang", chain_lang);
		Email.SendConfirmMail(email, code, from);
		response.sendRedirect("ConfirmMail.jsp");
	}

}

